const WebSocket = require('ws');
const MQTT = require('mqtt');
const CONFIG = require('./config/config')



const options = {
  headers: {
    'Cookie': 'ID=6588e84c0db3; view=2',
    'Origin': 'http://kj6eo.com:8901',
    'Pragma': 'no-cache',
    'Sec-Websocket-Extensions': 'permessage-deflate; client_max_window_bits',
    'Sec-Websocket-Key': '8etu6SRS+CA68s3BmzNaDA==',
    'Sec-Websocket-Version': '13',
    'Upgrade': 'websocket',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
  }
};

const socket = new WebSocket('ws://kj6eo.com:8901/~~stream?v=11', options);
console.log(111)
const URL = 'tcp://' + CONFIG.mqtt.host + ':' + CONFIG.mqtt.settings.port;

obj_mqtt_client = MQTT.connect(URL, {
    username: CONFIG.mqtt.username,
    password: CONFIG.mqtt.password,
})
// console.log('obj_mqtt_client',obj_mqtt_client)
obj_mqtt_client.on('error', function (err) {
    console.log(
     
        '设备与MQTT服务连接失败',err
    )
})
obj_mqtt_client.on('connect', function () {
    console.log(
     
        '设备与MQTT服务建立连接',
    )
})

socket.on('open', () => {
  console.log('Connected to WebSocket');
});

socket.on('message', (encodedData) => {
    const hexData =encodedData
    const encoder = new TextEncoder();
const uint8Array = encoder.encode(hexData);
obj_mqtt_client.publish('center/aerocraft_receive',uint8Array.toString(),(error) => {
    if (error) {
      console.error('Failed to publish message:', error);
    } else {
      console.log('Message published successfully');}});
});

socket.on('close', () => {
  console.log('WebSocket Connection Closed');
});

socket.on('error', (error) => {
  console.error(error);
});


